package my.sample.channel.datagram;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Arrays;

public class Client {

//	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Client.class);
	public static void main(String[] args) {
		
		if ( args.length < 8 ) {
			System.out.println("No sufficient inputs: ");
			System.out.println("<ipaddress> <port> <clienttext> <text> <count> <fold> <sentcount> <waittime>");
			System.out.println("<0>         <1>    <2>          <3>    <4>     <5>    <6>         <7>");
			System.exit(0);
		}
		
		InetSocketAddress ipAddress = null;
		DatagramChannel channel = null;
		String text = ""; 
		
		for ( int i = 0 ; i < Integer.parseInt(args[4]) ; i++ ) {                                                               
			text += args[3];
		}
		
		ByteBuffer[] sources = new ByteBuffer[Integer.parseInt(args[5])];
		sources[0] = ByteBuffer.wrap(args[2].getBytes());
		ByteBuffer headerBuffer = ByteBuffer.allocate(args[2].length() + 1);
		sources[0]  = headerBuffer;
		System.out.println("0-" + Arrays.toString(args[2].getBytes()) );
		for (int i = 1; i < Integer.parseInt(args[5]); i++ ) {
			ByteBuffer temp = ByteBuffer.allocate(text.getBytes().length);
//			System.out.println(text.getBytes());
			temp.put(text.getBytes());
			temp.flip();
			sources[i] = temp;
			System.out.println(i + "-" + Arrays.toString(temp.array()));
		}
		
//		System.out.println("final : " + Arrays.toString(sources));
		
		try {
			ipAddress = new InetSocketAddress(InetAddress.getByName(args[0]), Integer.parseInt(args[1]));
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
		
		try {
			channel = DatagramChannel.open();
			channel.connect(ipAddress);
			channel.socket().setSendBufferSize(131071);
			channel.configureBlocking(false);
			System.out.println("isBlocking " + channel.isBlocking());
//			System.out.println("connection status : " + channel.isConnected());
//			System.out.println("open status : " + channel.isOpen());
		} catch (IOException e) {
			try {
				channel.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
//		System.out.println("connection status : " + channel.isConnected());
//		System.out.println("open status : " + channel.isOpen());
//		ByteBuffer temp = ByteBuffer.allocate(text.getBytes().length);
		
		int sendCount = Integer.parseInt(args[6]);
		int waitTime = Integer.parseInt(args[7]);
		
		Selector selector = null;
		try {
			selector = Selector.open();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		SelectionKey key = null;
		try {
			
			for ( int i = 0 ; i < sendCount ; i++ ) {
			
				sources[1] = ByteBuffer.allocate(4).putInt(i);
				System.out.println("alter : " + Arrays.toString(sources[1].array()));
				channel.write(sources);
				
				key = channel.register(selector, SelectionKey.OP_READ);
				key.attach("murali");
				
				System.out.print("  " + i + "\r");
				for ( int j = 0; j < sources.length; j++) {
					sources[j].flip();
				}
				
				
				System.out.println("going to select");
				if ( selector.select() == 0 ) {
					System.out.println("selector select returns 0 ");
				}
				
				
				Thread.sleep(waitTime);
			}
			
			channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}